package com.fuxinglianbao.services;

import com.fuxinglianbao.models.CyclePeriod;
import com.fuxinglianbao.models.StarLevel;
import com.fuxinglianbao.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

@Service
public class BonusService {
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private UserService userService;

    @Autowired
    private StarLevelService starLevelService;

    @Autowired
    private CyclePeriodService cyclePeriodService;

    @Transactional
    public void processCycleCompletion(Long userId, int starLevel) {
        User user = userService.getUser(userId);
        CyclePeriod cycle = cyclePeriodService.findActiveCycle(userId, starLevel);
        StarLevel currentStarLevel = starLevelService.getStarLevel(starLevel);

        if (!cycle.isCompleted()) {
            throw new IllegalStateException("周期未完成");
        }

        // 获取当前星级的周期次数
        int cycleCount = cycle.getCycleCount();

        // 处理第二次成团的特殊情况
        if (cycleCount == 2) {
            handleSecondCycleCompletion(user, currentStarLevel);
        } else {
            // 非第二次成团，发放分红奖励
            distributeBonusReward(user, currentStarLevel);
        }

        // 执行强制复投
        processForcedReinvestment(user, currentStarLevel);

        // 创建新的活跃周期
        cyclePeriodService.createNewCyclePeriod(userId, starLevel);
    }

    private void handleSecondCycleCompletion(User user, StarLevel currentStarLevel) {
        // 计算升级所需总金额
        BigDecimal totalAmount = currentStarLevel.getBonusReward()
                .add(currentStarLevel.getForcedReinvestment());

        // 验证金额是否足够升级
        StarLevel nextStarLevel = starLevelService.getStarLevel(user.getStarLevel() + 1);
        if (nextStarLevel != null && totalAmount.compareTo(nextStarLevel.getPreChargeAmount()) == 0) {
            // 执行自动升级
            starLevelService.automaticUpgrade(user.getId());
        } else {
            throw new IllegalStateException("第二次成团金额计算错误");
        }
    }

    private void distributeBonusReward(User user, StarLevel starLevel) {
        BigDecimal bonusReward = starLevel.getBonusReward();
        
        // 更新用户分红余额（可提现余额）
        user.setBonusBalance(user.getBonusBalance().add(bonusReward));
        entityManager.merge(user);

        // 处理推荐奖励
        distributeReferralBonus(user, bonusReward);
    }

    private void distributeReferralBonus(User user, BigDecimal baseBonus) {
        // 直推奖励（10%）
        User directReferrer = user.getReferrer();
        if (directReferrer != null) {
            BigDecimal directBonus = baseBonus.multiply(BigDecimal.valueOf(0.10))
                    .setScale(2, RoundingMode.HALF_UP);
            directReferrer.setBonusBalance(directReferrer.getBonusBalance().add(directBonus));
            entityManager.merge(directReferrer);

            // 二级推荐奖励（5%）
            User secondLevelReferrer = directReferrer.getReferrer();
            if (secondLevelReferrer != null) {
                BigDecimal secondLevelBonus = baseBonus.multiply(BigDecimal.valueOf(0.05))
                        .setScale(2, RoundingMode.HALF_UP);
                secondLevelReferrer.setBonusBalance(secondLevelReferrer.getBonusBalance().add(secondLevelBonus));
                entityManager.merge(secondLevelReferrer);
            }
        }
    }

    private void processForcedReinvestment(User user, StarLevel starLevel) {
        BigDecimal forcedReinvestment = starLevel.getForcedReinvestment();
        
        // 更新用户预充余额（用于购物抵扣）
        user.setAvailableBalance(user.getAvailableBalance().add(forcedReinvestment));
        entityManager.merge(user);
    }

    @Transactional(readOnly = true)
    public BigDecimal calculateTotalBonus(Long userId) {
        User user = userService.getUser(userId);
        return user.getBonusBalance();
    }

    @Transactional
    public void withdrawBonus(Long userId, BigDecimal amount) {
        User user = userService.getUser(userId);
        
        if (user.getBonusBalance().compareTo(amount) < 0) {
            throw new IllegalArgumentException("可提现余额不足");
        }

        // 扣减分红余额（可提现余额）
        user.setBonusBalance(user.getBonusBalance().subtract(amount));
        entityManager.merge(user);

        // TODO: 实现提现到支付宝/微信/银行卡的具体逻辑
    }

    @Transactional
    public void processShoppingDiscount(Long userId, BigDecimal orderAmount) {
        User user = userService.getUser(userId);
        
        // 计算最大抵扣金额（订单总额的20%）
        BigDecimal maxDiscount = orderAmount.multiply(BigDecimal.valueOf(0.20))
                .setScale(2, RoundingMode.HALF_UP);
        
        // 检查用户可用余额
        BigDecimal availableBalance = user.getAvailableBalance();
        BigDecimal actualDiscount = availableBalance.min(maxDiscount);
        
        if (actualDiscount.compareTo(BigDecimal.ZERO) > 0) {
            // 扣减用户可用余额
            user.setAvailableBalance(availableBalance.subtract(actualDiscount));
            entityManager.merge(user);
        }
    }
}